package homework04.test03;

public class TicketSell02 extends Thread {

    /**
     * 因为继承了Thread类对象, 会new多个线程对象; 所以这里的火车票数量设置为静态, 多个对象共享
     */
    private static int ticketNum = 100;

    /**
     * 同步监视器使用静态对象, 才可以调用相关的wait 和notifyAll 方法
     */
    private static final Object obj = new Object();

    @Override
    public void run() {

        while (true) {

            synchronized (obj) { // 因为需要new多个线程对象, 所以这里的同步监视器需要使用静态对象; 并且调用静态对象的wait和notify方法
                obj.notifyAll();//唤醒其他线程
                if (ticketNum > 0) {//如果剩余车票数量大于0, 才能继续卖票
                    ticketNum--;
                    System.out.println(getName() + "卖掉了一张票, 剩余票数:" + ticketNum);

                    try {
                        //当前线程休眠100毫秒
                        Thread.sleep(100);
                        // 让出CPU, 进入阻塞状态
                        obj.wait(); //
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println("票卖光了");
                    break;
                }
            }
        }
    }

    public static void main(String[] args) {

        TicketSell02 t1 = new TicketSell02();
        t1.setName("窗口1");
        t1.start();

        TicketSell02 t2 = new TicketSell02();
        t2.setName("窗口2");
        t2.start();

        TicketSell02 t3 = new TicketSell02();
        t3.setName("窗口3");
        t3.start();

        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
